package jmine.tec.hydra.schedule;

import jmine.tec.hydra.HydraController;
import jmine.tec.hydra.api.HydraRequest;
import jmine.tec.hydra.domain.specification.HydraScheduledSpecification;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.dao.BeanNotFoundException;
import bancosys.tec.utils.date.Date;

/**
 * @author joao
 * @author piercio
 * @deprecated use jmine.tec.scheduling
 */
@Deprecated
public class HydraJob extends QuartzJobBean {

    public static final String JOB_GROUP = "scheduledHydra";

    public static final String SPECIFICATION_ID = "specificationId";

    public static final String CONTROLLER = "controller";

    private Long specificationId;

    private HydraController controller;

    /**
     * {@inheritDoc}
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        this.controller.getPersistenceController().startTransaction();
        boolean success = false;

        try {
            BaseDAO<HydraScheduledSpecification> dao = this.controller.getDAOFactory().getGenericDAO(HydraScheduledSpecification.class);
            HydraScheduledSpecification specification = dao.findByPk(this.specificationId);
            HydraRequest request = this.controller.send(new Date(), specification);
            context.setResult(request);
            success = true;
        } catch (BeanNotFoundException e) {
            throw new JobExecutionException("Não foi encontrada a integração a ser executada.", e);
        } finally {
            if (success) {
                this.controller.getPersistenceController().commit();
            } else {
                this.controller.getPersistenceController().rollback();
            }
        }
    }

    /**
     * @param specificationId the specificationId to set
     */
    public void setSpecificationId(Long specificationId) {
        this.specificationId = specificationId;
    }

    /**
     * @param controller o valor para o campo controller
     */
    public void setController(HydraController controller) {
        this.controller = controller;
    }
}